package com.fjl.filewriter;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;

import org.apache.tools.zip.ZipFile;

public class readZipTest
{

	public static void main(String[] args)
	{
		try
		{
//			 FileInputStream in = new FileInputStream(new
//			 File("D:\\转化的移动数据\\武汉市光谷\\MapGIS.amr"));
//			InputStream in = new FileInputStream("F:\\fjltest\\MapGIS Explorer.zip");
//			unzip(in, "F:\\");
			
//			unzip1();
			unZipFiles("F:\\fjltest\\MapGIS Explorer.zip", "F:\\");

//			 zip("F:\\fjltest\\MapGIS Explorer.zip", new
//			 File("F:\\fjltest\\MapGIS Explorer"));
			
			//文件复制
//			FileInputStream in = new FileInputStream(new File("F:\\fjltest\\MapGIS Explorer.zip"));
//			byte[] bytes = FileOperation.readInputStreamToBytes(in);
//			FileOperation.writeBytesFile(bytes, "F:\\MapGIS Explorer.zip");
			
//			FileOperation.writeInputStreamFile(in, "F:\\MapGIS Explorer.zip");

		}
		catch (FileNotFoundException e)
		{
			e.printStackTrace();
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
	}

	private static int k = 1; // 定义递归次数变量

	private static void zip(String zipFileName, File inputFile) throws Exception
	{
		System.out.println("压缩中...");
		ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFileName));
		BufferedOutputStream bo = new BufferedOutputStream(out);
		zip(out, inputFile, inputFile.getName(), bo);
		bo.close();
		out.close(); // 输出流关闭
		System.out.println("压缩完成");
	}

	private static void zip(ZipOutputStream out, File f, String base, BufferedOutputStream bo) throws Exception
	{ // 方法重载
		if (f.isDirectory())
		{
			File[] fl = f.listFiles();
			if (fl.length == 0)
			{
				out.putNextEntry(new ZipEntry(base + "/")); // 创建zip压缩进入点base
				System.out.println(base + "/");
			}
			for (int i = 0; i < fl.length; i++)
			{
				zip(out, fl[i], base + "/" + fl[i].getName(), bo); // 递归遍历子文件夹
			}
			System.out.println("第" + k + "次递归");
			k++;
		}
		else
		{
			out.putNextEntry(new ZipEntry(base)); // 创建zip压缩进入点base
			System.out.println(base);
			FileInputStream in = new FileInputStream(f);
			BufferedInputStream bi = new BufferedInputStream(in);
			int b;
			while ((b = bi.read()) != -1)
			{
				bo.write(b); // 将字节流写入当前zip目录
			}
			bi.close();
			in.close(); // 输入流关闭
		}
	}

	public static void unzip1()
	{
		long startTime = System.currentTimeMillis();
		try
		{
			ZipInputStream Zin = new ZipInputStream(new FileInputStream("D:\\转化的移动数据\\武汉市光谷\\MapGIS.amr"));// 输入源zip路径
			BufferedInputStream Bin = new BufferedInputStream(Zin);
			String Parent = "D:\\转化的移动数据\\武汉市光谷\\"; // 输出路径（文件夹目录）
			File Fout = null;
			ZipEntry entry;
			try
			{
				while ((entry = Zin.getNextEntry()) != null && !entry.isDirectory())
				{
					Fout = new File(Parent, entry.getName());
					if (!Fout.exists())
					{
						(new File(Fout.getParent())).mkdirs();
					}
					FileOutputStream out = new FileOutputStream(Fout);
					BufferedOutputStream Bout = new BufferedOutputStream(out);
					int b;
					while ((b = Bin.read()) != -1)
					{
						Bout.write(b);
					}
					Bout.close();
					out.close();
					System.out.println(Fout + "解压成功");
				}
				Bin.close();
				Zin.close();
			}
			catch (IOException e)
			{
				e.printStackTrace();
			}
		}
		catch (FileNotFoundException e)
		{
			e.printStackTrace();
		}
		long endTime = System.currentTimeMillis();
		System.out.println("耗费时间： " + (endTime - startTime) + " ms");
	}

	/**
	 * 解压ZIP文件
	 * 
	 * @param zipFileName ZIP文件
	 * @param outputDirectory 解压目的存放路径
	 */
	public static void unzip(InputStream zipFileName, String outputDirectory)
	{
		try
		{
			BufferedOutputStream dest = null;
			ZipInputStream in = new ZipInputStream(zipFileName);
			// 获取ZipInputStream中的ZipEntry条目，一个zip文件中可能包含多个ZipEntry，
			// 当getNextEntry方法的返回值为null，则代表ZipInputStream中没有下一个ZipEntry，
			// 输入流读取完成；
			ZipEntry entry = in.getNextEntry();
			while (entry != null)
			{
				// 创建以zip包文件名为目录名的根目录
				File file = new File(outputDirectory);
				file.mkdir();
				if (entry.isDirectory())
				{
					String name = entry.getName();
					name = name.substring(0, name.length() - 1);

					file = new File(outputDirectory + File.separator + name);
					file.mkdir();

				}
				else
				{
					int count;
					byte data[] = new byte[2048];
					file = new File(outputDirectory + File.separator + entry.getName());
					file.createNewFile();
					FileOutputStream out = new FileOutputStream(file);
					dest = new BufferedOutputStream(out, 2048);
					while ((count = in.read(data, 0, 2048)) != -1)
					{
						dest.write(data, 0, count);
					}
					dest.flush();
					dest.close();
				}
				// 读取下一个ZipEntry
				entry = in.getNextEntry();
			}
			in.close();
		}
		catch (FileNotFoundException e)
		{
			e.printStackTrace();
		}
		catch (IOException e)
		{
			// TODO 自动生成 catch 块
			e.printStackTrace();
		}
	}
	
	/**
	 * 解压(处理中文文件名乱码的问题)
	 * @param zipFileName
	 * @param extPlace
	 * @return
	 * @throws Exception
	 */
	 public static boolean unZipFiles(String zipFileName, String extPlace) throws Exception {
//		    System.setProperty("sun.zip.encoding", System.getProperty("sun.jnu.encoding"));
		        try {  
		            (new File(extPlace)).mkdirs();  
		            File f = new File(zipFileName);
		            ZipFile zipFile = new ZipFile(zipFileName,"GBK");  //处理中文文件名乱码的问题
		            if((!f.exists()) && (f.length() <= 0)) {  
		                throw new Exception("要解压的文件不存在!");  
		            }  
		            String strPath, gbkPath, strtemp;  
		            File tempFile = new File(extPlace);  
		            strPath = tempFile.getAbsolutePath();  
		            Enumeration<?> e = zipFile.getEntries();
		            while(e.hasMoreElements()){
		                ZipEntry zipEnt = (ZipEntry) e.nextElement();
		                gbkPath=zipEnt.getName();
		                if(zipEnt.isDirectory()){  
		                    strtemp = strPath + File.separator + gbkPath;  
		                    File dir = new File(strtemp);  
		                    dir.mkdirs();  
		                    continue;  
		                } else {
		                    //读写文件  
		                    InputStream is = zipFile.getInputStream((org.apache.tools.zip.ZipEntry) zipEnt);  
		                    BufferedInputStream bis = new BufferedInputStream(is);  
		                    gbkPath=zipEnt.getName();  
		                    strtemp = strPath + File.separator + gbkPath;  
		                  
		                    //建目录  
		                    String strsubdir = gbkPath;  
		                    for(int i = 0; i < strsubdir.length(); i++) {  
		                        if(strsubdir.substring(i, i + 1).equalsIgnoreCase("/")) {  
		                            String temp = strPath + File.separator + strsubdir.substring(0, i);  
		                            File subdir = new File(temp);  
		                            if(!subdir.exists())  
		                            subdir.mkdir();  
		                        }  
		                    }  
		                    FileOutputStream fos = new FileOutputStream(strtemp);  
		                    BufferedOutputStream bos = new BufferedOutputStream(fos);  
		                    int c;  
		                    while((c = bis.read()) != -1) {  
		                        bos.write((byte) c);  
		                    }
		                    bos.close();  
		                    fos.close();  
		                }
		            }
		            return true;
		        } catch(Exception e) {  
		            e.printStackTrace(); 
		            return false;
		        }  
		    }  
}
